#include "Queue.h"

void QueueInit(Queue* phead)
{
	//Queue* pf = (Queue*)malloc(sizeof(Queue));
	//if (pf == NULL)
	//{
	//	perror("malloc fail");
	//}
	//phead = pf;
	phead->head = NULL;
	phead->tail = NULL;
	phead->size = 0;
}

void QueueQestroy(Queue* phead)
{
	assert(phead);
	QNode* cur = phead->head;
	while (cur)
	{
		Queue* next = cur->next;
		free(cur);
		cur = next;
	}
	phead->head = NULL;
	phead->tail = NULL;
	phead->size = 0;
}

void QueuePush(Queue* phead, QDatatype x)
{
	assert(phead);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}
	newnode->next = NULL;
	newnode->val = x;
	if (phead->tail == NULL)
	{
		phead->head = phead->tail = newnode;
	}
	else
	{
		phead->tail->next = newnode;
		phead->tail = phead->tail->next;
	}
	phead->size++;
}

void QueuePop(Queue* phead)
{
	assert(phead);
	assert(!QueueEmpty(phead));
	if (phead->head->next == NULL)
	{
		free(phead->head);
		phead->head = phead->tail = NULL;
	}
	else
	{
		QNode* next = phead->head->next;
		free(phead->head);
		phead->head = next;
	}
	phead->size--;
	//QNode* head = phead->head;
	//QNode* next = phead->head->next;
	//free(head);
	//phead->head = next;
	//phead->size--;
}

bool QueueEmpty(Queue* phead)
{
	assert(phead);
	return phead->size == 0;
}

QDatatype QueueFront(Queue* phead)
{
	assert(phead);
	assert(!QueueEmpty(phead));
	return phead->head->val;
}

QDatatype QueueBack(Queue* phead)
{
	assert(phead);
	assert(!QueueEmpty(phead));
	return phead->tail->val;
}

int QueueSize(Queue* phead)
{
	assert(phead);
	assert(!QueueEmpty(phead));
	return phead->size;
}


void QueuePrint(Queue* phead)
{
	assert(phead);
	assert(!QueueEmpty(phead));
	QNode* cur = phead->head;
	while (cur)
	{
		printf("%d ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}